package com.foreveross.util;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.foreveross.crawl.common.cfg.PropertyUtils;
import com.foreveross.crawl.common.cfg.system.SystemPropertiesLoader;
import com.foreveross.crawl.vo.MachineInfo;
import com.foreveross.crawl.vo.Message;

/** 
 * @ClassName: 工具类 
 * @Description: TODO
 * @author luofangyi
 * @date 2014-7-22 上午9:45:48 
 *  
 */ 
public class WebcrawlUtil {

	private static WebcrawlUtil util = new WebcrawlUtil();
	
	public static WebcrawlUtil getInstance(){
		return util;
	}
	/**  
	 * @Description: 获取节点名称
	 * @param message
	 * @return
	 * @author luofangyi
	 * @date 2014-7-22 上午9:47:02 
	 */ 
	public String getNodeSn(Message message){
		String nodeSn = "";
		nodeSn = getMachineIp(message) + getPort() + getNodeName();
		return nodeSn;
	}
	
	/**  
	 * @Description: 获取当前机器IP
	 * @param message
	 * @return
	 * @author luofangyi
	 * @date 2014-7-22 上午9:57:17 
	 */ 
	public String getMachineIp(Message message){
		String ip = "";
		MachineInfo machineInfo = ((List<MachineInfo>)message.getBody()).get(0);
		
		boolean obtainIp = PropertyUtils.getBooleanProperty(PropertesCustom.SYSTEM_NET_OBTAIN_IP, SystemPropertiesLoader.FILE_NAME);
		if(obtainIp){//是否从联网获取IP
			try {
				ip = obtainNetIp();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(ip == ""){
			ip = machineInfo.getIp();
		}
		return ip;
	}
	
	/**  
	 * @Description: 联网获取IP
	 * @return
	 * @author luofangyi
	 * @throws Exception 
	 * @date 2014-7-14 下午12:05:35 
	 */ 
	private String obtainNetIp() throws Exception{
		
		String url = "http://20140507.ip138.com/ic.asp";
		HttpClientUtil httpClient = HttpClientUtil.getInstance();
		String responseMsg = httpClient.executeByGet(url);
		String regEx = "\\[(.+?)\\]";
		return getPatternString(responseMsg, regEx);
	}
	
	private String getPatternString(String content, String regEx){
		Pattern p=Pattern.compile(regEx, Pattern.DOTALL|Pattern.MULTILINE);
		Matcher m=p.matcher(content);
		String retStr = "";
		if(m.find()){
			retStr=  m.group(1);
		}
		return retStr.trim().replaceAll("&nbsp;", "");
	}
	
	/**  
	 * @Description: 获取端口号
	 * @return
	 * @author luofangyi
	 * @date 2014-7-22 上午10:19:04 
	 */ 
	public String getPort(){
		return PropertyUtils.getProperty(
				PropertesCustom.SYSTEM_PORT,
				SystemPropertiesLoader.FILE_NAME, "8080");
	}
	
	/**  
	 * @Description: 获取节点名称
	 * @return
	 * @author luofangyi
	 * @date 2014-7-22 上午10:19:33 
	 */ 
	public String getNodeName(){
		return NodeInfoPropertyUtil.getValueByProperty(NodeInfoPropertyUtil.NODE_NAME, "node1");
	}
}
